package com.example.Utils;

import java.util.List;

import com.example.entity.DbWeather;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;

public class DBUtil {
	public static final String DATABASE = "MyDB";// 数据库名
	public static final String TABLE = "weather";
	public static final int VERSION = 1;
	public static final String DATARESULT = "dataResult";
	public static final String CITY = "city";
	public static final String _ID = "id";// 下划线代表主键

	public static void toast(Context context, String text) {
		Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 数据库查询全表，仅在开启数据库开启时操作
	 * 
	 * @param db
	 *            操作的数据库
	 * @param source
	 *            内部映射集合
	 * @return 如果为true 成功，false失败
	 */
	public static boolean query(SQLiteDatabase db, List<String> source) {
		List<String> data = source;

		Cursor cursor = db.query(TABLE, null, null, null, null, null, null);
		if (cursor == null) {
			return false;
		}
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			
			String dataResult = cursor.getString(cursor.getColumnIndex(DATARESULT));
			data.add(dataResult);
		}
		return true;

	}
/**
 * 数据库插入方法，插入一条数据
 * @param db 数据
 * @param person 插入的对象
 * @return 
 */
	public static boolean insert(SQLiteDatabase db, DbWeather dbweather) {
		ContentValues values = new ContentValues();
		values.put(DATARESULT, dbweather.getDataResult());
		values.put(CITY, dbweather.getCity());
		long ret = db.insert(TABLE, null, values);
		if (ret == -1) {
			return false;
		}
		return true;
	}
	public static boolean delete(SQLiteDatabase db,String city){
		
		
		long raw=db.delete(TABLE," city=?", new String[]{city});
		if (raw==0) {
			return false;
		}
		return true;
	}
	public static String querySingle(SQLiteDatabase db,String city){
	Cursor cursor=db.query(TABLE, null, CITY+"=?", new String[]{city}, null, null, null);
	String dataResult;
	if (cursor.moveToFirst()) {
		dataResult = cursor.getString(cursor.getColumnIndex(DATARESULT));
		return dataResult;
	}else
		return null;
		 
		
		
	}
	public static boolean update(SQLiteDatabase db,DbWeather  dbweather){
		ContentValues values = new ContentValues();
		values.put(DATARESULT, dbweather.getDataResult());
		long raw=db.update(TABLE,values, CITY+"=?", new String[]{dbweather.getCity()});
		if (raw>0) {
			return true;
		}
		return false ;
	}

}
